﻿
package com.cbts.service.info.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author 邱鸿辉
 *
 */
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.cbts.dao.DepartmentDao;
import com.cbts.dao.TravelStandardDao;
import com.cbts.dao.UserGroupDao;
import com.cbts.dao.UserInfoDao;
import com.cbts.entity.TravelStandard;
import com.cbts.entity.UserGroup;
import com.cbts.entity.UserInfo;
import com.cbts.service.info.UserInfoService;
import com.cbts.util.Constant;
import com.cbts.util.MD5Util;
import com.cbts.util.Page;

public class UserInfoServiceImpl implements UserInfoService {
	
	
	private UserInfoDao userInfoDao;//与员工相关的相关数据库访问
	private UserGroupDao  userGroupDao;//与用户组相关的数据库访问
	private DepartmentDao departmentDao;//与部门相关的数据库访问
	private TravelStandardDao travelStandardDao;//与差旅标准相关得数据库访问
	/*private UserGroup userGroup;//
*/	public TravelStandardDao getTravelStandardDao() {
		return travelStandardDao;
	}
	public void setTravelStandardDao(TravelStandardDao travelStandardDao) {
		this.travelStandardDao = travelStandardDao;
	}
	public DepartmentDao getDepartmentDao() {
		return departmentDao;
	}
	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public UserInfoDao getUserInfoDao() {
		return userInfoDao;
	}
	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}
	/*public List<UserGroup> getUserGroupList() {
		return userGroupList;
	}
	public void setUserGroupList(List<UserGroup> userGroupList) {
		this.userGroupList = userGroupList;
	}*/
	public UserGroupDao getUserGroupDao() {
		return userGroupDao;
	}
	public void setUserGroupDao(UserGroupDao userGroupDao) {
		this.userGroupDao = userGroupDao;
	}
	/*public UserGroup getUserGroup() {
		return userGroup;
	}
	public void setUserGroup(UserGroup userGroup) {
		this.userGroup = userGroup;
	}*/
	/*private List<UserGroup> userGroupList;*/

	/* 
	 * @see com.cbts.service.info.UserInfoService#getAllUserInfo(int pageNum)
	 */
	//获取所有的员工
	public Page<UserInfo> getAllUserInfo(int pageNum) {
		// zqd 上午09:17:43
		return userInfoDao.findAllByPage(pageNum, Constant.PAGE);
	}
	/* 
	 * @see com.cbts.service.info.UserInfoService#getAllUserInfo()
	 */
	//获取所有的员工
	public Page<UserInfo> getAllUserInfo() {
		// zqd 上午09:17:43
		return userInfoDao.findAll();
	}
	//增加员工
	public boolean addUserInfo(UserInfo ui) {
		
		ui.setPwd(MD5Util.encode2hex(ui.getPwd()));//密码加密MD5
		if(userInfoDao.save(ui))
			return true;
		return false;
	}
	//批量增加员工，上传员工信息excel表并解析保存到数据库
	public boolean addBatchUserInfo(File file,String fileName) {
		try{
			FileInputStream fis = new FileInputStream(file);
			
			Workbook book = null;
			if(fileName.toLowerCase().endsWith("xls"))//如果上传的文件为xls文件，则升成HSSFWorkbook实例
				book = new HSSFWorkbook(fis);
			else if(fileName.toLowerCase().endsWith("xlsx"))//如果上传的文件为xlsx文件，则升成XSSFWorkbook实例
				book = new XSSFWorkbook(fis);
			else 
				return false;//如果不是xls文件或者xlsx文件则返回false
			Sheet sheet = book.getSheetAt(0);//获取文件内容所在的sheet
			List<UserInfo> userInfoList = new ArrayList<UserInfo>();//用来存储表中的员工信息
			for(int i=2;i<sheet.getLastRowNum()+1;i++)//遍历sheet
			{
				Row row = sheet.getRow(i);//获取当前行
				UserInfo userInfo = new UserInfo();
				int j=0;
				String userid  = null;
				if(row.getCell(j) != null)//对于那些非enum类型的非空数据，先获取其单元格，为空则返回false，不为空则获取其值
				{							//然后去掉空格之类的字符，假如为空串则返回false
					userid = row.getCell(j++).getStringCellValue();
					if("".equals(userid.trim()))
						return false;
				}
				else
					return false;
				String userName  = null;
				if(row.getCell(j) != null)
				{
					userName = row.getCell(j++).getStringCellValue();
					if("".equals(userName.trim()))
						return false;
				}
				else
					return false;
				double count = 0.0;//对于那些可以为空的数据，先获取其单元格，单元格若存在则获取其值，假如是字符串则去掉空格之类的字符
				if(row.getCell(j) != null)
					count = row.getCell(j).getNumericCellValue();
				j++;
				String email = null;
				if(row.getCell(j) != null)
					email = row.getCell(j).getStringCellValue().trim();
				j++;
				String emailValidated = row.getCell(j++).getStringCellValue();//对于那些非空的enum类型直接取其值
				String gender = row.getCell(j++).getStringCellValue();
				String authority = row.getCell(j++).getStringCellValue();
				String departmentName = null;
				if(row.getCell(j) != null)
					departmentName = row.getCell(j).getStringCellValue().trim();
				j++;
				String position = null;
				if(row.getCell(j) != null)
					position = row.getCell(j).getStringCellValue().trim();
				j++;
				String userGroupName = null;
				if(row.getCell(j) != null)
					userGroupName = row.getCell(j).getStringCellValue().trim();
				j++;
				String password  = null;
				if(row.getCell(j) != null)
				{
					password = row.getCell(j++).getStringCellValue();
					if("".equals(password.trim()))
						return false;
				}
				else
					return false;
				
				Date registerTime = null;
				if(row.getCell(j)== null)//对于注册时间，假如为空，则以导入时间为注册时间
					registerTime = new Date();
				else
					registerTime = row.getCell(j).getDateCellValue();			
					userInfo.setUserid(userid);//设置用户的相关信息
					userInfo.setUserName(userName);
					userInfo.setCount(count);
					userInfo.setEmail(email);
					userInfo.setEmailValidated(emailValidated);
					userInfo.setGender(gender);
					userInfo.setAuthority(authority);
					if(departmentName != null &&!"".equals(departmentName))//用户属于某个部门时，根据部门名获取部门
						userInfo.setDepartment(departmentDao.getDepartmentByDepartmentName(departmentName));
					userInfo.setPosition(position);
					if(userGroupName != null &&!"".equals(userGroupName))//用户属于某个用户组时，根据用户组名获取用户组
						userInfo.setUserGroup(getUserGroupByUserGroupName(userGroupName));
					userInfo.setPwd(password);
					userInfo.setRegisterTime(registerTime);
				
				userInfoList.add(userInfo);	
			}
			userInfoDao.saveOrUpdate(userInfoList);//用户不存在则增加，存在则更新
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	/*public boolean deleteUserInfo(UserInfo ui) {
		
		if(userInfoDao.delete(ui))
			return true;
		return false;
	}*/
	//根据员工id获取员工
	public UserInfo getUserInfo(String id) {
		
		return userInfoDao.get(id);
	}
	/*public List<UserInfo> getUserInfoByDepartment(String id,int firstResult,int maxResult) {
		
		String hql = "from UserInfo u where u.department.departmentId = ?";
		return userInfoDao.findByProperty(hql, new Object[]{id}, firstResult, maxResult).getPageItems();
	}
	public List<UserInfo> getUserInfoByGroup(String id,int firstResult,int maxResult) {
		
		String hql = "from UserInfo u where u.userGroup.userGroupId = ?";
		return userInfoDao.findByProperty(hql, new Object[]{id}, firstResult, maxResult).getPageItems();
	}*/
/*	public List<UserInfo> getUserInfoByEmail(String email,int firstResult,int maxResult){
		String hql = "from UserInfo u where u.email = ?";
		return userInfoDao.findByProperty(hql, new Object[]{email}, firstResult, maxResult).getPageItems();
	}*/
	public boolean updateUserInfo(UserInfo ui) {
		if(userInfoDao.update(ui))
			return true;
		return false;
	}
	//增加一个用户组
	public boolean addUserGroup(UserGroup userGroup) {
		
		if(userGroupDao.save(userGroup))
			return true;
		return false;
	}
	public boolean deleteUserGroup(UserGroup userGroup) {
		
		if(userGroupDao.delete(userGroup))
			return true;
		return false;
	}
	
/*	public UserGroup getUserGroup(int id) {
		
		
		return userGroupDao.get(id);
	}

	public boolean moveToUserGroup(UserInfo userInfo, int userGroupId) {
		
		return false;
	}*/
	public boolean updateUserGroup(UserGroup userGroup) {
		if(userGroupDao.update(userGroup))
			return true;
		return false;
	}
	//获取所有用户组
	public List<UserGroup> getAllUserGroup() {
		
		return userGroupDao.findAll().getPageItems();
	}
	public Page<UserGroup> getAllUserGroupByPage(){
		return userGroupDao.findAll();
	}
/*	public List<UserInfo> getUserGroupUsers(int GroupId, int firstResult,
			int maxResult) {
		
		return null;
	}*/
	//登录
	public boolean login(String userid,String pwd) {
		UserInfo userInfo = userInfoDao.get(userid);
		if (userInfo.getUserid()!=null&&!userInfo.getUserid().isEmpty()&&userInfo.getUserid().length()>0) {
			
			if (userInfo.getUserid().equals(userid)&&MD5Util.validate(pwd, userInfo.getPwd())) {
				Map session=ServletActionContext.getContext().getSession();
				session.put("authority",userInfo.getAuthority());
				return true;
				
			}
		}
		return false;
	}
	//批量删除员工
	public boolean deleteUserInfoList(List<UserInfo> userInfoList) {
		
		if(userInfoDao.deleteList(userInfoList))
			return true;
		return false;
	}
	//批量修改员工信息
	public boolean updateUserInfoList(List<UserInfo> userInfoList) {
		
		if(userInfoDao.updateList(userInfoList))
			return true;
		return false;
	}
	//批量删除或者修改员工信息
	/*public void updateOrDeleteUserInfo(List<UserInfo> userInfoList,String check,int operate){
		
			String[] arraycheckbox = check.split(", ");//分割check得到被勾选的userid
			ArrayList<UserInfo> selectedList = new ArrayList<UserInfo>();//用于存储被勾选的员工
			String gemail = null,lemail = null;//gemail,guserInfo的email;lemail,luserInfo的email
			
			for (int j = 0; j < userInfoList.size(); j++)
				System.out.println("列表中的员工id"+userInfoList.get(j).getUserid()+
						"用户组"+userInfoList.get(j).getUserGroup().getUserGroupName()+
						"部门"+userInfoList.get(j).getDepartment().getDepartmentName());
			
			for (int i = 0; i < arraycheckbox.length; i++)
			{
				System.out.println(arraycheckbox[i]);
				UserInfo guserInfo =userInfoDao.get(arraycheckbox[i]);//根据userid从数据库get到的员工
				if (operate == 0&&!userInfoList.isEmpty())
				{
					for (int j = 0; j < userInfoList.size(); j++)
					{
						UserInfo luserInfo = userInfoList.get(j);//传进来的userInfoList中获取到的
						if (luserInfo.getUserid().equals(arraycheckbox[i])){	//被勾选的员工
							System.out.println("列表中的员工id"+luserInfo.getUserid());
							System.out.println("列表中的"+luserInfo.getUserGroup().getUserGroupId());
							//System.out.println("数据库读取的"+guserInfo.getUserGroup().getUserGroupId());
							//System.out.println("数据库员工id"+guserInfo.getUserid());
							//System.out.println("__________");
							
							guserInfo.setUserName(luserInfo.getUserName());//修改员工的相关信息 名字
							guserInfo.setGender(luserInfo.getGender());	//性别
							if("".equals(luserInfo.getDepartment().getDepartmentId()))	//部门
								guserInfo.setDepartment(null);
							else
								guserInfo.setDepartment(luserInfo.getDepartment());
							guserInfo.setPosition(luserInfo.getPosition());	//职位
							
							System.out.println(luserInfo.getUserGroup().getUserGroupName());
							if(luserInfo.getUserGroup().getUserGroupId() == null)	//用户组
								guserInfo.setUserGroup(null);
							else
								guserInfo.setUserGroup(luserInfo.getUserGroup());
							gemail = guserInfo.getEmail();
							lemail = luserInfo.getEmail();
							if(gemail!= null && !gemail.equals(lemail)|| lemail != null && !lemail.equals(guserInfo.getEmail()))
								guserInfo.setEmailValidated("否");	
							guserInfo.setEmail(luserInfo.getEmail());	//email
							guserInfo.setAuthority(luserInfo.getAuthority());		//权限
							
							
							break;
						}
					}
				}
				selectedList.add(guserInfo);
			}
			
			if(!selectedList.isEmpty())
			{
				if (operate == 1) {
						deleteUserInfoList(selectedList);// 批量删除用户信息
					
				} else if (operate == 0) {
						for(int i=0;i<selectedList.size();i++)
						{
							if(selectedList.get(i).getDepartment()!= null &&selectedList.get(i).getDepartment().getDepartmentId().trim().equals(""))
								selectedList.get(i).setDepartment(null);
							if(selectedList.get(i).getUserGroup()!=null&&selectedList.get(i).getUserGroup().getUserGroupId()== null)
								selectedList.get(i).setUserGroup(null);
						}
						updateUserInfoList(selectedList);// 批量更新用户信息
				} 
			}
		
	}*/
	
	public void updateOrDeleteUserInfo(List<UserInfo> userInfoList,String check,int operate){
		//得到信息
		//整理信息
		//判断操作
		//循环处理
		
		if(operate == 1){
			List<UserInfo> list = new ArrayList<UserInfo>();
			for (int j = 0; j < userInfoList.size(); j++)
				list.add(userInfoDao.get(userInfoList.get(j).getUserid()));
			if(this.deleteUserInfoList(list))	System.out.println("success");
		}else if(operate == 0){
			/*for (int j = 0; j < userInfoList.size(); j++){
				userInfoList.get(j).setPwd(userInfoDao.get(userInfoList.get(j).getUserid()).getPwd());
			}*/
			if(this.updateUserInfoList(userInfoList))	System.out.println("success");
		}
		
	}
	
	
	public boolean deleteUserGroupList(List<UserGroup> userGroupList) {
		
		if(userGroupDao.deleteList(userGroupList))
			return true;
		return false;
	}
	public boolean updateUserGroupList(List<UserGroup> userGroupList) {
		
		if(userGroupDao.updateList(userGroupList))
			return true;
		return false;
	}
	public List<UserGroup> getSelectedUserGroup(List<UserGroup> userGroupList,String check,String operate){
		
			String[] arraycheckbox = check.split(", ");//分割check得到被勾选用户组的userGroupId
			ArrayList<UserGroup> selectedList = new ArrayList<UserGroup>();//用来存储被勾选的用户组

			for (int i = 0; i < arraycheckbox.length; i++)
			{
				UserGroup userGroup = userGroupDao.get(Integer.parseInt(arraycheckbox[i]));//获取相应的用户组
				if ("修改".equals(operate)&&!userGroupList.isEmpty())
				{
					for (int j = 0; j < userGroupList.size(); j++)
					{
						if (userGroupList.get(j).getUserGroupId() == Integer.parseInt(arraycheckbox[i]))//被勾选的用户组
						{
							userGroup.setUserGroupName(userGroupList.get(j).getUserGroupName());//修改用户组的相关信息
							userGroup.setTravelStandard(userGroupList.get(j).getTravelStandard());
							break;
						}
					}
				}	
				selectedList.add(userGroup);	
			}
			return selectedList;
			
	
	}
	//批量增加或者修改员工信息
	public boolean saveOrUpdateUserInfo(List<UserInfo> userInfoList) {
		
		if(userInfoDao.saveOrUpdate(userInfoList))
			return true;
		return false;
	}
	//获取所有的差旅标准
	public List<TravelStandard> getAllTravelStandard() {
		
		return travelStandardDao.findAll().getPageItems();
	}
	//根据用户组名获取用户组
	public UserGroup getUserGroupByUserGroupName(String userGroupName) {
		
		return userGroupDao.getUserGroupByUserGroupName(userGroupName);
	}
	public boolean sameUserGroupNameExist(int userGroupId,String userGroupName){
		String hql= "and o.userGroupId != ? and o.userGroupName = ?";
		return userGroupDao.queryUnique(hql, new Object[]{userGroupId,userGroupName})!=null;
	}
	public List<UserInfo> getUserInfoByDepartment(String departmentId) {
		String hql = "and o.department.departmentId = ?";
		return userInfoDao.findByProperty(hql,new Object[]{ departmentId}, -1, -1).getPageItems();
	}
	/* 
	 * @see com.cbts.service.info.UserInfoService#getUserGroup(int)
	 */
	public UserGroup getUserGroup(int id) {
		// zqd 上午09:17:03
		return userGroupDao.get(id);
	}
	
	
}
